<?php
/**
 * 团检相关
 *
 * User: kaikaic
 * Date: 2018/11/24
 * Time: 23:34
 */

namespace app\api\controller;

use app\api\service\MainService;
use app\exam\service\GroupApplyService;
use controller\BasicApi;
use think\Request;

class Group extends BasicApi {

    // 团检最大人数
    const MAX_PERSON = 5000;

    // 预算最大金额
    const MAX_BUDGET = 2000;

    /**
     * 提交团检申请
     *
     * ex.game.com/api/group/apply?contacts=李经理&contact_number=13900112255&name=华谊集团&persons=100&budget=160
     */
    public function apply() {
        $contacts = trim($this->request->param("contacts"));
        $contactNumber = trim($this->request->param("contact_number"));
        $name = trim($this->request->param("name"));                    // 企业名称
        $persons = intval($this->request->param("persons"));
        $budget = intval($this->request->param("budget", 0));

        if (!$contacts || !$contactNumber || !$name || !$persons) {
            $this->outputJsonError("请填写必要信息");
        }

        if (!$this->isPhoneNumber($contactNumber)) {
            $this->outputJsonError("电话号码错误, 如果是固话，必须形如(xxxx-xxxxxxxx)", 404);
        }

        if ($persons > self::MAX_PERSON) {
            $this->outputJsonError("人数太多了，是不是再考虑下", 401);
        }
        if ($budget > self::MAX_BUDGET) {
            $this->outputJsonError("预算太多了，是不是再考虑下", 402);
        }

        $record = GroupApplyService::getInstance()->haveApply($contacts, $contactNumber);
        if ($record) {
            $this->outputJsonError("已经提交，请等待审核", 405);
        }

        $params = array();
        $params['contacts'] = $contacts;
        $params['contact_number'] = $contactNumber;
        $params['name'] = $name;
        $params['persons'] = $persons;
        $params['budget'] = $budget;
        $params['comment'] = "";
        $params['status'] = 1;
        $params['create_time'] = time();

        $result = GroupApplyService::getInstance()->insert($params);
        if (!$result) {
            $this->outputJsonError("提交失败，请稍后重试", 406);
        }else {
            $this->outputJsonSuccess(array());
        }
    }

    /**
     * 匹配座机电话、手机号码
     */
    private function isPhoneNumber($phone) {
        $isMobile = "/^1[3-5,8]{1}[0-9]{9}$/";
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";

        if(preg_match($isTel, $phone)) {
            return true;
        }

        if(preg_match($isMobile, $phone)) {
            return true;
        }

        return false;
    }
}